package net.m510.autosurfer.saison;

import java.net.URI;
import java.util.List;
import java.util.logging.Logger;

import net.m510.autosurfer.common.DocumentPostProcess;
import net.m510.autosurfer.common.exception.CannotLoginException;
import net.m510.autosurfer.core.DocumentChecker;
import net.m510.autosurfer.core.Parameters;
import net.m510.autosurfer.core.exception.UserProcessException;

import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.FormElement;

/**
 * @author mgoto
 *
 */
public class SaisonLogin extends DocumentPostProcess implements DocumentChecker {
	private static final Logger log = Logger.getLogger(SaisonLogin.class.getName());

	private String userId;
	private String password;
	
	public SaisonLogin() {
		this(null,null);
	}
	public SaisonLogin(CloseableHttpClient client, HttpClientContext context) {
		super(client, context);
		super.log = log;
	}
	@Override
	protected List<NameValuePair> getRequestParameters(Document doc) {
		FormElement form = doc.getAllElements().forms().get(0);
		Parameters p = Parameters.create(form);
		p.put("inputId", this.userId);
		p.put("inputPassword", this.password);
		return p.asNameValueList();
	}

	@Override
	protected URI getUri(Document doc) {
		String action = doc.select("form[name=_USA01Form]").attr("action");
		HttpHost host = context.getTargetHost();
		URI uri = URI.create(host.toURI());
		log.fine("first uri = "+uri);
		uri = uri.resolve(action);
		log.fine("resolved uri = "+uri);
		return uri;
	}
	
	@Override
	public void check(Document doc) throws UserProcessException {
		final String ERR_UNCORRECT_PASSWD1 = "IDもしくはパスワードの入力値に誤りがあります。";
		// ログインエラーチェック
		if ( doc.body().html().contains(ERR_UNCORRECT_PASSWD1)) {
			CannotLoginException cle = new CannotLoginException(
					doc.body().getElementsContainingOwnText(ERR_UNCORRECT_PASSWD1).first().text()
					);
			cle.setDocument(doc);
			throw cle;
		}
	}
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}